package com.hbxs.folder.logic;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.hbxs.folder.bean.CustomGenericException;
import com.hbxs.folder.bean.FileBean;
import com.hbxs.folder.bean.Result;
import com.hbxs.folder.constant.Constant;
import com.hbxs.folder.constant.FolderTypeEnum;
import com.hbxs.folder.modules.folder.service.FastFileService;
import com.hbxs.folder.modules.folder.service.FolderService;
import com.hbxs.folder.pojo.entity.FolderDO;
import com.hbxs.folder.pojo.vo.FolderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.http.HttpStatus;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 附件处理
 */
@Slf4j
@Service
public class AnnexLogic {

    @Autowired
    private FolderService folderService;
    @Autowired
    private FastFileService fastFileService;

    public Result<List<FolderVO>> upload(HttpServletRequest request, List<MultipartFile> files) throws IOException {
        List<FolderVO> folderVOList = Lists.newArrayList();
        log.info("上传文件数量" + files.size() + "个文件");
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                log.error("上传第" + (i++) + "个文件失败");
                return  Result.generate(Result.CodeList.SERVER_ERROR,"上传第" + (i++) + "个文件失败",null);
            }
            String suffix = FileUtil.extName(file.getOriginalFilename());
            String name = FileUtil.mainName(file.getOriginalFilename());
            String capitalSuffix = suffix.toUpperCase();
            FileBean fileBean = new FileBean();
            FolderDO folderDO = new FolderDO();
            folderDO.setType(FolderTypeEnum.getFolderType(capitalSuffix));
            if (StrUtil.equals(folderDO.getType(),FolderTypeEnum.Forbid.getName())) {
                return  Result.generate(Result.CodeList.FILE_FORMAT_ERROR,"禁止上传次文件",null);
            }

            fileBean.setGroup(Constant.EVENT_FILE_GROUP);
            fileBean.setSize(file.getSize());
            fileBean.setSuffixName(suffix);
            fileBean.setInputStream(file.getInputStream());

            Set<MetaData> metaDataSet = Sets.newHashSet();
            folderDO.setRemark(DateUtil.now()+"上传的文件");
            fileBean.setMetaDataSet(metaDataSet);
            try {
                fastFileService.uploadFile(fileBean);

                folderDO.setSize(fileBean.getSizeMb()+"MB");
                folderDO.setRelease(new Date());
                folderDO.setGmtCreate(new Date());
                folderDO.setGmtModified(new Date());
                folderDO.setDataStats(1);
                folderDO.setName(name);
                folderDO.setSuffix(suffix);
                folderDO.setPath(fileBean.getPath());
                folderService.save(folderDO);
                FolderVO folderVO = new FolderVO();
                BeanUtil.copyProperties(folderDO,folderVO);
                folderVOList.add(folderVO);
            } catch (Exception e) {
                log.error(e.toString(), e);
                return  Result.generate(Result.CodeList.SERVER_ERROR,"上传第" + (i++) + "个文件失败",null);
            }
        }
        return Result.success("success",folderVOList);
    }

    public void getData(String id, HttpServletResponse response) throws IOException, CustomGenericException {
        FolderDO folderDO = folderService.getById(id);
        if (folderDO==null){
            throw new CustomGenericException(Result.CodeList.NOT_FOUND.getCode(),"附件不存在");
        }
        FileBean fileBean = new FileBean();
        fileBean.setGroup(Constant.EVENT_FILE_GROUP);
        fileBean.setPath(folderDO.getPath());
        try {
            fastFileService.downloadFile(fileBean);
            Tika tika = new Tika();
            response.setStatus(HttpStatus.SC_OK);
            response.setContentType(tika.detect(fileBean.getPath()));
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "inline;filename="+ URLEncoder.encode(folderDO.getName()+"."+folderDO.getSuffix(), "UTF-8"));
            IoUtil.copy(fileBean.getInputStream(),response.getOutputStream());
            response.flushBuffer();
        }catch (Exception e){
            log.error(e.toString());
        }finally {
            fileBean.getInputStream().close();
        }
    }

    /**
     * 断点下载
     * @param id
     * @param response
     * @param range
     * @throws IOException
     * @throws CustomGenericException
     */
    public void getDataBreakpoint(String id, HttpServletResponse response, String range) throws IOException, CustomGenericException {
        FolderDO folderDO = folderService.getById(id);
        if (folderDO==null){
            throw new CustomGenericException(Result.CodeList.NOT_FOUND.getCode(),"附件不存在");
        }
        FileBean fileBean = new FileBean();
        fileBean.setGroup(Constant.EVENT_FILE_GROUP);
        fileBean.setPath(folderDO.getPath());
        try {
            fastFileService.downloadFile(fileBean);
        }catch (Exception e){
            log.error(e.toString());
            fileBean.getInputStream().close();
            throw new CustomGenericException(Result.CodeList.SERVER_ERROR.getCode(),"系统错误");
        }
        //开始下载位置
        long startByte = 0;
        //结束下载位置
        long endByte = fileBean.getInputStream().available() - 1;

        //有range的话
        if (range != null && range.contains("bytes=") && range.contains("-")) {
            range = range.substring(range.lastIndexOf("=") + 1).trim();
            String ranges[] = range.split("-");
            try {
                //判断range的类型
                if (ranges.length == 1) {
                    //类型一：bytes=-2343
                    if (range.startsWith("-")) {
                        endByte = Long.parseLong(ranges[0]);
                    }
                    //类型二：bytes=2343-
                    else if (range.endsWith("-")) {
                        startByte = Long.parseLong(ranges[0]);
                    }
                }
                //类型三：bytes=22-2343
                else if (ranges.length == 2) {
                    startByte = Long.parseLong(ranges[0]);
                    endByte = Long.parseLong(ranges[1]);
                }

            } catch (NumberFormatException e) {
                startByte = 0;
                endByte = fileBean.getInputStream().available() - 1;
            }
        }

        //要下载的长度（为啥要加一问小学数学老师去）
        long contentLength = endByte - startByte + 1;
        //文件名
        String fileName = FileUtil.getName(fileBean.getPath());
        //文件类型 request.getServletContext().getMimeType(fileName);
        Tika tika = new Tika();
        String contentType = tika.detect(fileBean.getPath());


        //各种响应头设置
        //参考资料：https://www.ibm.com/developerworks/cn/java/joy-down/index.html
        //坑爹地方一：看代码
        response.setHeader("Accept-Ranges", "bytes");
        //坑爹地方二：http状态码要为206
        response.setStatus(HttpStatus.SC_PARTIAL_CONTENT);
        response.setContentType(contentType);
        response.setHeader("Content-Type", contentType);
        //这里文件名换你想要的，inline表示浏览器直接实用（我方便测试用的）
        //参考资料：http://hw1287789687.iteye.com/blog/2188500
        response.setHeader("Content-Disposition", "inline;filename="+ URLEncoder.encode(folderDO.getName()+"."+folderDO.getSuffix(), "UTF-8"));
        response.setHeader("Content-Length", String.valueOf(contentLength));
        //坑爹地方三：Content-Range，格式为
        // [要下载的开始位置]-[结束位置]/[文件总大小]
        response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + fileBean.getInputStream().available());
        // 下载文件能正常显示中文
        //response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(folderDO.getName()+"."+folderDO.getSuffix(), "UTF-8"));
        BufferedOutputStream outputStream = null;
        //已传送数据大小
        long transmitted = 0;
        try {

            outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[4096];
            int len = 0;
            fileBean.getInputStream().skip(startByte);
            //坑爹地方四：判断是否到了最后不足4096（buff的length）个byte这个逻辑（(transmitted + len) <= contentLength）要放前面！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
            //不然会会先读取randomAccessFile，造成后面读取位置出错，找了一天才发现问题所在
            while ((transmitted + len) <= contentLength && (len = fileBean.getInputStream().read(buff)) != -1) {
                outputStream.write(buff, 0, len);
                transmitted += len;
                //停一下，方便测试，用的时候删了就行了
                Thread.sleep(10);
            }
            //处理不足buff.length部分
            if (transmitted < contentLength) {
                len = fileBean.getInputStream().read(buff, 0, (int) (contentLength - transmitted));
                outputStream.write(buff, 0, len);
                transmitted += len;
            }

            outputStream.flush();
            response.flushBuffer();
            fileBean.getInputStream().close();
            log.debug("下载完毕：" + startByte + "-" + endByte + "：" + transmitted);
        } catch (ClientAbortException e) {
            log.debug("用户停止下载：" + startByte + "-" + endByte + "：" + transmitted);
            //捕获此异常表示拥护停止下载
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            fileBean.getInputStream().close();
        }
    }

    /**
     * 删除文件
     * @param id
     * @return
     */
    public Result<String> del(String id){
        FolderDO folderDO = folderService.getById(id);
        if (folderDO==null){
            throw new CustomGenericException(Result.CodeList.NOT_FOUND.getCode(),"附件不存在");
        }
        FileBean fileBean = new FileBean();
        fileBean.setGroup(Constant.EVENT_FILE_GROUP);
        fileBean.setPath(folderDO.getPath());
        fastFileService.deleteFile(fileBean);
        folderService.removeById(id);

        return Result.success("删除成功","");
    }


}
